#pragma once

#include <memory>
#include <vector>
#include <unordered_map>

#include <QObject>
#include <QString>
#include <QMetaType>

#include "ThostFtdcMdApi.h"

#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/daily_file_sink.h>

// DLL 导出宏定义
#if defined(Q_OS_WIN)
    #if defined(MARKET_LIBRARY)
        #define MARKET_EXPORT Q_DECL_EXPORT
    #else
        #define MARKET_EXPORT Q_DECL_IMPORT
    #endif
#else
    #define MARKET_EXPORT
#endif

namespace MarketEngine {

// CTP API 创建函数指针类型定义
typedef CThostFtdcMdApi* (*CreateFtdcMdApiFunc)(const char*, bool, bool);

// CTP连接状态
enum class ConnectionStatus {
    Disconnected,    // 未连接/已断开
    Connecting,      // 连接中
    Connected,       // 已连接
    Disconnecting    // 断开中
};

// 使用静态map存储状态描述
inline const QString& getStatusString(ConnectionStatus status)
{
    static const std::unordered_map<ConnectionStatus, QString> statusMap{
        {ConnectionStatus::Disconnected,  "Disconnected"},
        {ConnectionStatus::Connecting,    "Connecting"},
        {ConnectionStatus::Connected,     "Connected"},
        {ConnectionStatus::Disconnecting, "Disconnecting"}
    };
    
    static const QString unknown = "Unknown";
    auto it = statusMap.find(status);
    return it != statusMap.end() ? it->second : unknown;
}

struct MarketConfig {
    QString brokerID;              // 经纪商ID
    QString userID;                // 用户ID
    QString password;              // 密码
    QString frontAddress;          // 前置机地址
    QString mdDllPath;             // CTP行情库路径
    QString flowPath;              // 流数据路径
    std::vector<QString> symbols;  // 订阅的合约列表
    
    struct {
        bool enableUdp{false};     // 是否启用UDP
        int heartbeatTimeout{15};  // 心跳超时时间(秒)
    } connection;
};

class MARKET_EXPORT Engine : public QObject {
    Q_OBJECT
    
public:
    explicit Engine(QObject* parent = nullptr);
    ~Engine();
    
    // 禁用拷贝
    Engine(const Engine&) = delete;
    Engine& operator=(const Engine&) = delete;
    
    // 核心功能接口
    bool init(const MarketConfig& config, std::shared_ptr<spdlog::logger> logger = nullptr);
    void start();
    void stop();
    
    // 订阅接口
    bool subscribe(const std::vector<QString>& symbols);
    bool unsubscribe(const std::vector<QString>& symbols);
    
    // 状态查询
    ConnectionStatus connectionStatus() const { return status; }
    
    // 获取已订阅的合约列表
    std::vector<QString> getSubscribedSymbols() const;
    
signals:
    void onTick(const CThostFtdcDepthMarketDataField& tick);
    void onStatusChanged(ConnectionStatus status);
    void onError(int errorID, const QString& errorMsg);
    
private:
    class EnginePrivate;
    std::unique_ptr<EnginePrivate> d_ptr;
    ConnectionStatus status{ConnectionStatus::Disconnected};
    std::shared_ptr<spdlog::logger> logger;  // 添加 logger 成员
};

} // namespace MarketEngine

// 在命名空间外注册类型
Q_DECLARE_METATYPE(MarketEngine::ConnectionStatus)